package logic

import (
	"context"
	"errors"
	"fmt"
	"io"

	"nhooyr.io/websocket"
	"nhooyr.io/websocket/wsjson"
)

type User struct {
	Username       string `json:"username"`
	conn           *websocket.Conn
	MessageChannel chan string
}

type msg struct {
	Msg_head string `json:"type"`
	Content  string `json:"content"`
}

// sendMessage 用于给用户发送消息
func (u *User) SendMessage(ctx context.Context) {
	for msg := range u.MessageChannel {
		fmt.Println("SendMessage:", msg)
		wsjson.Write(ctx, u.conn, msg)
	}
}

// CloseMessageChannel 避免 goroutine 泄露
func (u *User) CloseMessageChannel() {
	fmt.Println("user quit")
	close(u.MessageChannel)
}

func (u *User) ReceiveMessage(ctx context.Context) error {
	var (
		receiveMsg map[string]string
		err        error
	)
	for {
		err = wsjson.Read(ctx, u.conn, &receiveMsg)
		if err != nil {
			// 判定连接是否关闭了，正常关闭，不认为是错误
			var closeErr websocket.CloseError
			if errors.As(err, &closeErr) {
				return nil
			} else if errors.Is(err, io.EOF) {
				return nil
			}
			return err
		}
		fmt.Println("&receiveMsg", receiveMsg, receiveMsg["type"])
		aaa := msg{"HeartBeat", ""}
		if receiveMsg["type"] == "heartbeat" {
			err = wsjson.Write(ctx, u.conn, aaa)
			if err != nil {
				return nil
			}
		}

		// 给用户发送的消息
		//Broadcaster.Broadcast(receiveMsg["content"])
		Broadcaster.Broadcast(u, receiveMsg["content"])
	}
}

func NewUser(conn *websocket.Conn, username string) *User {
	user := &User{
		Username:       username,
		conn:           conn,
		MessageChannel: make(chan string, 8),
	}

	return user
}
